package com.samp.tools.lire;

import net.semanticmetadata.lire.builders.GlobalDocumentBuilder;
import net.semanticmetadata.lire.imageanalysis.features.global.AutoColorCorrelogram;
import net.semanticmetadata.lire.imageanalysis.features.global.CEDD;
import net.semanticmetadata.lire.imageanalysis.features.global.FCTH;
import net.semanticmetadata.lire.utils.LuceneUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 由于lire的lucene版本是基于5.2.1的，当前引入的是6的lucene，所以会报错，可以至solr-se中查看。
 */
public class IndexImage {
	
	private static final Logger logger = LoggerFactory.getLogger(IndexImage.class);
	
	private static boolean createIndex(IndexWriter iw, String imgPathDir, String imageId) throws Exception {
		GlobalDocumentBuilder globalDocumentBuilder = new GlobalDocumentBuilder(false);
		globalDocumentBuilder.addExtractor(CEDD.class);
		globalDocumentBuilder.addExtractor(FCTH.class);
		globalDocumentBuilder.addExtractor(AutoColorCorrelogram.class);
		try {
			//String imageFilePath = imgPathDir;
			//如果增量更新imageId已存在，则更新
			boolean update = false;
//			if( searcher != null ){
//				TopDocs result = searcher.search(new TermQuery(new Term(DocumentBuilder.FIELD_NAME_IDENTIFIER,imageId)), 10);
//				if( result != null && result.scoreDocs.length > 0 ){
//					update = true;
//				}
//			}
			BufferedImage img = ImageIO.read(new FileInputStream(imgPathDir));
			Document document = null;
			try{
				document = globalDocumentBuilder.createDocument(img,imageId);
			}catch(ArrayIndexOutOfBoundsException e){
				logger.warn("index without AutoColorCorrelogram, imageId="+imageId);
				globalDocumentBuilder = new GlobalDocumentBuilder(false);
				globalDocumentBuilder.addExtractor(CEDD.class);
				globalDocumentBuilder.addExtractor(FCTH.class);
				document = globalDocumentBuilder.createDocument(img,imageId);
			}
			if( update ){
				logger.info("index ingore update for imageId = "+imageId);
				//iw.updateDocument(new Term(DocumentBuilder.FIELD_NAME_IDENTIFIER,imageId), document);
				//暂时不更新，因为只是更新，会导致图片查询不到。
			}else{
				logger.info("index add for imageId = "+imageId);
				iw.addDocument(document);
			}
		} catch (Exception e) {
			logger.error("image index fail,image path:"+imgPathDir+",imageId="+imageId,e);
			return false;
		}
		logger.info("image index sucess,image path:"+imgPathDir+",imageId="+imageId);
		
		return true;
	}

	public static void main(String[] args) {
        String seriesIndexPath = "D:\\nas\\lire\\index\\GIF";
		String imgPathDir = "D:\\nas\\lire\\data\\GIF";
        Path dir = Paths.get(imgPathDir);
		try {
            IndexWriter iw = LuceneUtils.createIndexWriter(seriesIndexPath,false, LuceneUtils.AnalyzerType.WhitespaceAnalyzer);
            try( DirectoryStream<Path> stream = Files.newDirectoryStream(dir) ){
                for(Path path : stream){
                    if( !Files.isDirectory(path) ){
                        String rawPath = imgPathDir+"\\"+path.getFileName();
                        String imageId = path.getFileName().toString().split("\\.")[0];
                        System.out.println("process......rawPath="+rawPath+", imageId="+imageId);
                        createIndex(iw,rawPath,imageId);
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
			iw.commit();
			iw.close();
			//LuceneUtils.commitWriter(iw);
			//LuceneUtils.closeWriter(iw);
//			if( reader != null ){
//				reader.close();
//			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
